package service

import (
	"chat.com/library"
	"chat.com/model"
	"chat.com/pkg/logger"
)

/*用于操作和查询各种用户状态的服务*/

// 查询用户是否在线
func IsUserOnline(appId int64, userId int64) (ok bool, info *model.UserOnline) {
	if appId == 0 { // 全平台查询
		for _, appId := range GetAppIds() {
			ok, info = checkUserOnline(appId, userId)
			if ok == true {
				break
			}
		}
	} else { // 特定平台查询
		ok, info = checkUserOnline(appId, userId)
	}

	return
}

// 查询用户是否在线, 通过redis查询
func checkUserOnline(appId int64, userId int64) (ok bool, info *model.UserOnline) {
	// 从Redis获取接收者连接信息
	info, err := library.GetUserOnlineInfo(library.GenUserOnlineKey(appId, userId))
	if err != nil || !info.IsOnline() {
		logger.Debug("用户不在线, %d, %d, %s", appId, userId, err)
		ok = false
		return
	}

	ok = true
	return
}

// 判断是否是本机用户
func IsUserLocal(info *model.UserOnline) (ok bool) {
	if info.AccServerName == "" {
		return true
	}

	return false
}

// 添加好友关系
func AddSingleFriend(senderId int64, recieverId int64) (ok bool) {
	if err := model.NewSingleFriend(senderId, recieverId); err != nil {
		return false
	}

	return true
}

// 添加好友关系
func JoinGroup(groupId int64, senderId int64) (ok bool) {
	if _, err := model.NewGroupMember(groupId, senderId); err != nil {
		return false
	}

	return true
}
